<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\GridRequest;
use App\Model\Grid;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Toastr;

class GridController extends Controller
{
    protected $fields = [
        'img' => ' ',
        'url' => ' ',
        'sindex' => 0
    ];


    public function index()
    {
        $data = Grid::orderBy('id','desc')->paginate(20);
        return view('admin.grid.index',['data'=>$data]);

    }

    public function add()
    {
        $data = [];
        foreach ($this->fields as $field => $default) {
            $data[$field] = old($field, $default);
        }
        return view('admin.grid.add',['data'=>$data]);
    }


    public function add_post(GridRequest $request){
        $info = new Grid();

        foreach (array_keys($this->fields) as $field) {
            $info->$field = !empty($request->input($field)) ?$request->input($field) : '';
        }
        $info->status = 0;
        $info->save();
        return redirect('/admin/grid/index')->withSuccess('添加成功！');
    }

    public function edit($id)
    {
        $info = Grid::find($id);
        if(!$info){
            return redirect('/admin/grid/index')->withErrors('找不到对象!');
        }
        foreach (array_keys($this->fields) as $field) {
            $data[$field] = old($field, $info->$field);
        }
        $data['id'] = (int)$id;
        return view('admin.grid.edit', ['data'=>$data]);
    }



    public function edit_post(Request $request)
    {
        $id = $request->input('id');
        $info = Grid::find((int)$id);
        foreach (array_keys($this->fields) as $field) {
            $info->$field = !empty($request->input($field)) ?$request->input($field) : '';
        }
        $info->save();
        return redirect('/admin/grid/index')->withSuccess('编辑成功！');
    }

    public function delete($id)
    {
        $tag = Grid::find((int)$id);
        if ($tag) {
            $tag->delete();
        } else {
            Toastr::error('删除失败');
            return redirect()->back();
        }
        Toastr::success('删除成功');
        return redirect()->back();
    }

    public function up_down(Request $request){
        $return = array();
        do{
            $id = $request->input('id');
            if(empty($id)){
                $return['code'] = 101;
                $return['message'] = '缺少参数';
                break;
            }
            $info = Grid::where('id',$id)->first();
            if(empty($info)){
                $return['code'] = 102;
                $return['message'] = '对象不存在';
                break;
            }
            if($info->status == 0){
                $info->status = 1;
            }else{
                $info->status = 0;
            }
            $info->save();
            $return['code'] = 0;
            $return['message'] = '操作成功';
            break;

        }while (false);
        return response()->json($return);
    }
}
